<template>
	<view class="order_pay" :style="viewColor">
		<view class="order_count">
			<view class="pay_wrap">
				<view class="pay_price">
					付款给商家
					<!-- <priceFormat :price="payPrice" weight intSize="52" floatSize="40" labelSize="40"></priceFormat> -->
				</view>
				<view class="pay_shops">
					<view class="pay_title">{{merchantInfo.mer_name}}</view>
					<image src="../../../static/images/logos.png" mode=""></image>
				</view>
			</view>

			<view class="pay_input">
				<view class="pay_wrap">
					<view class="pay_input_title">金额</view>
					<div class="item pay_flex">
						<span>￥</span>
						<input type="number" placeholder="输入金额" placeholder-class="placeholder" v-model="money"
							required />
					</div>
				</view>
			</view>
		</view>
		<view class="payment boder-24 bg-f">
			<view class="btn">
				<view class="button acea-row row-center-wrapper" @click="goPay()">确认支付</view>
				<!-- <view class="wait-pay" @click="waitPay">暂不支付</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	// +----------------------------------------------------------------------
	// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
	// +----------------------------------------------------------------------
	// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
	// +----------------------------------------------------------------------
	// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
	// +----------------------------------------------------------------------
	// | Author: CRMEB Team <admin@crmeb.com>
	// +----------------------------------------------------------------------
	let app = getApp();
	import {
		HTTP_REQUEST_URL,
		HEADER,
		TOKENNAME
	} from '@/config/app';
	import {
		mapGetters
	} from 'vuex';
	import {
		configMap
	} from '@/utils';
	//import countDown from '@/components/countDown';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		getUserInfo,
		getOpenidxcx
	} from '@/api/user.js';
	import {
		orderPay,
		integralOrderPay,
		getCashierOrder,
		getOrderPayTypeList,
		maPai,
		orderMapai_order,
		orderMapai_pay
	} from '@/api/order.js';

	export default {
		components: {
			//	countDown
		},
		data() {
			return {
				invalidTime: 0,
				mapai_id: '',
				order_id: '',
				payPrice: '',
				order_type: '',
				//pay_type: '',
				number: 0,
				payMode: this.orderPayList,
				merchantInfo: {},
				bianmami: '',
				money: '',
				pay_type: '',
				open_id: ''
			};
		},
		computed: {
			...mapGetters(['isLogin', 'viewColor', 'orderPayList']),
			...configMap(['hide_mer_status']),
		},
		watch: {
			// orderPayList:{
			// 	handler(nVal,oVal){
			// 		if(nVal && this.order_id){
			// 			this.payMode= nVal;
			// 			this.getOrderConfig()
			// 		}
			// 	},
			// 	immediate: true,
			// 	deep:true
			// }
		},
		onLoad(options) {
			console.log(options)
				// #ifdef MP-WEIXIN
			    let url = unescape(decodeURI(options.q))
			    var obj = {};
			    //如果字符串里面存在?
			    if (url.indexOf("?") != -1) {
			      //从url的索引1开始提取字符串
			      var str = url.substring(url.indexOf("?")+1);
			      //如果存在&符号，则再以&符号进行分割
			      var arr = str.split("&");
			      //遍历数组
			      for (var i = 0; i < arr.length; i++) {
			        // obj对象的属性名 = 属性值，unescape为解码字符串
			        obj[arr[i].split("=")[0]] = unescape(arr[i].split("=")[1]);
			      }
			    }
			    console.log(obj);
				this.mapai_id = obj.bianmami
				uni.setStorageSync('mapai_id', options.bianmami)
				// #endif
				// #ifdef H5
			if (options.bianmami) {
				this.mapai_id = options.bianmami
				uni.setStorageSync('mapai_id', options.bianmami)
			}
		// #endif
			if (uni.getStorageSync('mapai_id')) {
				this.mapai_id = uni.getStorageSync('mapai_id')
			}
			/* if(uni.getStorageSync('wxcode')){
				let code = uni.getStorageSync('wxcode')				
				this.getopenId(code)
			} */
			uni.setStorageSync('backPayurl', '/pages/users/pay_page/index?bianmami=' + this.mapai_id)
			this.getPayInfo()

			// #ifdef H5
			var ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				console.log("这是微信浏览器");
				this.pay_type = '2'
			} else {
				console.log("这是普通浏览器");
				this.pay_type = '1'
			}
			// #endif

		},
		onReady() {
			let Url = HTTP_REQUEST_URL,
				header = HEADER;
			let that = this
			// #ifdef MP-WEIXIN
			uni.login({
				provider: 'weixin',
				onlyAuthorize: true,
				success(res) {
					if (res.code) {
						console.log(res.code)
						uni.request({
							url: Url + '/api/getOpenidxcx', //仅为示例，
							method: 'POST',
							data: {
								type: '2',
								code: res.code
							},
							header: {
								'Content-type': 'application/json'
							},
							success: (res) => {
								var datas = res.data
								console.log(datas)
								if (datas.status == 200) {
									that.open_id = datas.data.openid
									// uni.showToast({
									// 	title: datas.msg,
									// 	icon: 'none'
									// })								 
								} else {
									uni.showToast({
										title: datas.msg,
										icon: 'none'
									})
								}
							}
						})
						// that.codeVal = res.code
					} else {
						uni.showToast({
							title: '授权失败',
							icon: 'error',
							duration: 2000
						})
					}
				}
			})
			// #endif
		},
		methods: {		
			getPayInfo() {
				let Url = HTTP_REQUEST_URL,
					header = HEADER;
				let that = this
				//console.log(that.mapai_id)
				uni.request({		
					url: Url + '/api/mapai/' + that.mapai_id, //仅为示例，
					method: 'GET',
					header: {
						'Content-type': 'application/json'
					},
					success: (res) => {
						var datas = res.data
						console.log(datas)
						if (datas.status == 200) {
							that.merchantInfo = datas.data
							that.bianmami = datas.data.bianmami
							uni.showToast({
								title: uni.getStorageSync('openid'),
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: datas.message,
								icon: 'none'
							})
						}
					}
				})
				
			},
			close: function() {
				this.$emit('onChangeFun', {
					action: 'payClose'
				});
			},
			
			goPay() {
				if (this.money == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入金额',
					})
					return false;
				}
				// #ifdef MP-WEIXIN
				this.pay_type = '3'
				// #endif

				orderMapai_order({
					bianmami: this.bianmami,
					money: this.money,
					pay_type: this.pay_type
				}).then((res) => {
					console.log('res', res)
					if (res.status == 200) {
						// console.log(res)
						let datas = res.data
						if (datas.xianjin = 0) {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						} else {
							this.goPayzf(res.data.order_sn)
						}

					} else {
						//console.log('授权登录')
						toLogin()
					}
					console.log(res)
				}).catch(err => {
					
					console.log(err, '报错信息')
						toLogin()
					


				});
			},
			goPayzf(order_sn) {
				let that = this;
				if (uni.getStorageSync('openid') == '' && that.pay_type == 2) {
					uni.navigateTo({
						url: '/pages/users/wechat_login/index',
					})
					return false;
				}
				// #ifdef MP-WEIXIN
				const provider = 'wxpay';
				// #endif
				orderMapai_pay({
					order_sn: order_sn,
					open_id: uni.getStorageSync('openid')
				}).then((res) => {
					if (res.status == 200) {
						if (this.pay_type == 1) {
							window.location.href = res.data.info
						} else {
							uni.showLoading({
								title: '支付中...',
								mask: true
							})
							const payParams = res.data.info
							if (typeof WeixinJSBridge === "undefined") {
								if (document.addEventListener) {
									document.addEventListener('WeixinJSBridgeReady', () => {
										that.executePayment(payParams)
									}, false)
								} else if (document.attachEvent) {
									document.attachEvent('WeixinJSBridgeReady', () => {
										that.executePayment(payParams)
									})
									document.attachEvent('onWeixinJSBridgeReady', () => {
										that.executePayment(payParams)
									})
								}
								uni.hideLoading()
								uni.showToast({
									title: '正在初始化支付环境...',
									icon: 'none'
								})
								return
							}
							const paymentResult = that.executePayment(payParams)
							console.log(paymentResult)
							// 4. 处理支付结果
							if (paymentResult) {
								uni.showToast({
									title: '您已支付',
									icon: 'none'
								})
								console.log('您已支付')
							} else {
								uni.showToast({
									title: '您已取消支付',
									icon: 'none'
								})
							}
						}
					} else {
						console.log('授权登录')

						toLogin()
					}
					console.log(res)
				})
			},
			executePayment(info) {
				const payParams = info
				return new Promise((resolve, reject) => {
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							appId: payParams.appId,
							timeStamp: payParams.timeStamp,
							nonceStr: payParams.nonceStr,
							package: payParams.package,
							signType: payParams.signType,
							paySign: payParams.paySign
						},
						(res) => {
							if (res.err_message === 'get_brand_wcpay_request:ok') {
								resolve(true) // 支付成功
							} else if (res.err_message === 'get_brand_wcpay_request:cancel') {
								resolve(false) // 用户取消
							} else {
								reject(new Error(res.err_message || '支付失败'))
							}
						}
					)
				})
			},


		}
	};
</script>

<style scoped lang="scss">
	.order_pay {
		padding: 88rpx 0;
	}

	.payment {
		margin-top: 80rpx;
	}

	.pay_price {
		font-weight: bold;
		padding-bottom: 20rpx;
	}

	.pay_wrap {
		width: 92%;
		margin: 0 4%;
	}

	.pay_flex {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.pay_shops {
		display: flex;
		justify-content: space-between;
		align-items: center;

		image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 100%;
		}

	}

	.pay_input {
		background-color: #fff;
		border-radius: 40rpx 40rpx 0 0;
		padding: 20rpx 0 200rpx 0;
		margin-top: 40rpx;

		.pay_input_title {
			font-size: 24rpx;
			color: #282828;
		}

		.item {
			margin-top: 50rpx;
			padding-bottom: 40rpx;
			border-bottom: 2rpx solid #aaa;

			span {
				font-size: 50rpx;
				color: #030303;
				width: 20%;
			}

			input {
				color: #000;
				width: 75%;
				font-size: 40rpx;
			}
		}
	}

	.pay_time {
		margin-top: 28rpx;
	}

	.payment .item {
		height: 130rpx;
		padding: 0 30rpx;
	}

	.payment .item .left {
		width: 580rpx;
	}

	.payment .item .left .text {
		width: 500rpx;
	}

	.payment .item .left .text .name {
		font-size: 28rpx;
		color: #282828;
	}

	.payment .item .left .text .info {
		font-size: 22rpx;
		color: #999;
	}

	.payment .item .left .text .info .money {
		color: #ff9900;
	}

	/deep/radio .uni-radio-input.uni-radio-input-checked,
	/deep/radio .wx-radio-input.wx-radio-input-checked {
		border: 1px solid var(--view-theme) !important;
		background-color: var(--view-theme) !important;
	}

	.btn {
		position: fixed;
		left: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		bottom: 30rpx;
		bottom: calc(30rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		bottom: calc(30rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
	}

	.wait-pay {
		color: #aaa;
		font-size: 24rpx;
		padding-top: 20rpx;
	}

	.button {
		width: 690rpx;
		height: 90rpx;
		border-radius: 45rpx;
		color: #ffffff;
		background-color: var(--view-theme);
	}
</style>